package com.dferreira.languagesteach.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.os.StatFs;
import android.preference.PreferenceManager;

import com.dferreira.languagesteach.constants.Constants;

import java.io.File;

public class DataPaths {
    /* Repository info */
    private final Context context;
    private final SharedPreferences settings;
    private final String sdCardPath;
    private final String internalPath;

    /**
     * Constructor
     *
     * @param context global information about an application environment.
     */
    public DataPaths(Context context) {
        String installDestinationKey;

        installDestinationKey = Constants.INSTALL_DESTINATION_KEY;

        this.context = context;
        this.settings = PreferenceManager.getDefaultSharedPreferences(context);
        this.sdCardPath = Environment.getExternalStorageDirectory()
                .getAbsolutePath();
        this.internalPath = context.getDir(installDestinationKey,
                Context.MODE_PRIVATE).getAbsolutePath();
    }

    /**
     * Verify if there exist any sdcard mounted
     *
     * @return false   -> no sdcard available
     * true    -> sdcard available
     */
    public boolean sdCardIsAvailable() {
        String sdCardState;
        sdCardState = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(sdCardState);
    }


    /**
     * @return Path where the packages should be installed
     */
    public String getPackagesPath() {
        boolean writeOnSDCard;
        String installDestination;
        String packagesFolder;
        String separator;
        String onSDCardKey;

        onSDCardKey = Constants.ON_SDCARD;
        writeOnSDCard = settings.getBoolean(onSDCardKey,
                sdCardIsAvailable());
        installDestination = Constants.INSTALL_DESTINATION;
        packagesFolder = Constants.PACKAGES_FOLDER;
        separator = File.separator;
        if (writeOnSDCard) {
            return sdCardPath + separator + installDestination + separator
                    + packagesFolder;
        } else {
            return internalPath + separator + installDestination + separator
                    + packagesFolder;
        }
    }

    /**
     * @return Number of bytes free in the path from the packages
     */
    public Long getAvailableSpaceFromPackagesPath() {
        boolean writeOnSDCard;
        String onSDCardKey;
        StatFs pathState;
        long availableSpace;

        onSDCardKey = Constants.ON_SDCARD;
        writeOnSDCard = settings.getBoolean(onSDCardKey, sdCardIsAvailable());
        if (writeOnSDCard) {
            if (!sdCardIsAvailable()) {
                return (long) 0;
            }
            pathState = new StatFs(sdCardPath);
        } else {
            pathState = new StatFs(internalPath);
        }
        availableSpace = pathState.getAvailableBlocks() * pathState.getBlockSize();
        return availableSpace;
    }


    /**
     * @return name from the database
     */
    @SuppressWarnings("SameReturnValue")
    public String getDatabaseName() {
        return Constants.DATABASE_NAME;
    }

    /**
     * @return time from the connection timeout
     */
    @SuppressWarnings("SameReturnValue")
    public int getConnectTimeout() {
        return Constants.CONNECTION_TIMEOUT;
    }

    /**
     * @return false   -> means that network is unavailable
     * true    -> exist some network available
     */
    public boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager
                .getActiveNetworkInfo();
        return (activeNetworkInfo != null)
                && (activeNetworkInfo.isConnectedOrConnecting());
    }

    /**
     * @return false    ->  does not search for updates when the app is starting
     * true     -> will search for updates when the app is starting
     */
    public boolean searchUpdates() {
        String searchUpdatesKey;
        Boolean defaultValue;
        searchUpdatesKey = Constants.SEARCH_UPDATES_KEY;
        defaultValue = Constants.search_updates_default_value;
        return settings.getBoolean(searchUpdatesKey, defaultValue);
    }

    /**
     * @return Name from the file who describes the repository
     */
    @SuppressWarnings("SameReturnValue")
    public String getRepositoryDescriptionFile() {
        return Constants.REPOSITORY_DESCRIPTION_FILE;
    }

    /**
     * @return URL where the repository exists
     */
    public String getRepositoryUrl() {
        String repositoryUrlKey;

        repositoryUrlKey = Constants.REPOSITORY_URL_KEY;

        return settings.getString(repositoryUrlKey, Constants.repository_url_default_value);
    }

    /**
     * @return result from state of the package
     */
    @SuppressWarnings("SameReturnValue")
    public Integer packageStateResult() {
        return 0;
    }
}
